import axios from "axios";
// import Vue from "vue";
import router from "@/router";
import store from "@/store";
import qs from "qs";
//引入vant的UI框架
import { Toast } from "vant";
import Config from "@/config/index";
// import { getToken } from '@/lib/util'
const baseURL = Config.baseUrl;
const statusName = Config.response.statusName;
const statusCode = Config.response.statusCode;
const msgName = Config.response.msgName;
const dataName = Config.response.dataName;
const logoutUrl = Config.logoutUrl;
const tokenName = Config.request.tokenName;

let loadingToast;

class HttpRequest {
  constructor(
    baseUrl = baseURL,
    code = statusName,
    status = statusCode,
    message = msgName,
    data = dataName,
    logout_url = logoutUrl,
    token = tokenName
  ) {
    this.baseUrl = baseUrl;
    this.code = code;
    this.status = status;
    this.message = message;
    this.data = data;
    this.logout_url = logout_url;
    this.token = token;
    /* 队列，把请求的url放进去，如果队列变空，则意味着没有请求了，可以关闭loading */
    this.queue = {};
    // console.log(this.baseUrl);
  }
  /* axios的默认配置 */
  getInsideConfig() {
    // let token = window.localStorage.getItem(this.token) || "";
    const config = {
      baseURL: this.baseUrl,
      headers: {
        "content-type": "application/x-www-form-urlencoded"
        // [this.token]: token
      },
      method: "get"
    };
    return config;
  }
  /* 当请求数为0时，关闭loading动画 */
  distroy(url) {
    delete this.queue[url];
    if (!Object.keys(this.queue).length) {
      // 关闭loading动画
      loadingToast.clear();
    }
  }
  /* 当请求数大于0时，开启loading动画 */
  loading() {
    if (Object.keys(this.queue).length > 0) {
      // 执行loading函数
      loadingToast = Toast.loading({
        // mask: true,
        duration: 0,
        // loadingType: 'spinner',
        message: "加载中..."
      });
    }
  }
  /* 拦截器 */
  interceptors(instance, url) {
    let token = window.localStorage.getItem(tokenName);
    // 请求前
    instance.interceptors.request.use(
      config => {
        // 把当前url放入queue队列中
        this.queue[url] = true;
        // 添加一个全局的loading,如果队列不为0，则执行loading函数
        this.loading();
        // 在headers上添加token
        if (token) {
          config.headers[this.token] = token;
        }
        return config;
      },
      error => {
        // 对请求错误做些什么
        console.error("请求参数：" + JSON.stringify(error));
        return Promise.reject(error);
      }
    );
    // 添加响应拦截器
    instance.interceptors.response.use(
      // 对响应数据做点什么
      res => {
        // 关闭loading
        this.distroy(url);
        switch (res.data.code) {
          case 403:
            this.goToLogin();
            break;
        }
        return res.data;
      },
      // 对响应错误做点什么
      error => {
        console.log(error);
        // 关闭loading
        this.distroy(url);
        // 如果是登录过期错误，则前往登录页面
        if (error.response) {
          switch (error.response.status) {
            case 401:
              this.goToLogin();
              break;
          }
        }
        // 如果有错误信息，则显示错误信息
        if (error[this.data] && error[this.message]) {
          Toast.fail(error[this.message]);
        }
        return Promise.reject(error);
      }
    );
  }
  /* 跳转到登陆页面 */
  goToLogin() {
    window.localStorage.removeItem(tokenName);
    router.replace({
      path: "login",
      query: {
        redirect: router.currentRoute.fullPath
      } // 将跳转的路由path作为参数，登录成功后跳转到该路由
    });
  }
  /* ajax方法 */
  req(options) {
    const instance = axios.create();
    if (options.data) {
      let data = qs.stringify(options.data);
      options.data = data;
    }
    let reqOptions = Object.assign(this.getInsideConfig(), options);
    // console.log(reqOptions);
    this.interceptors(instance, reqOptions.url);
    return instance(reqOptions);
  }
}

export default HttpRequest;
